<template>
  <table class="table table-striped table-sm">
    <caption>
      增加附件
    </caption>
    <tr v-for="(info, index) of attachments">
      <td class="col-2">{{ info.fileName }}</td>
      <td class="col-2">
        <input
          type="text"
          class="form-control form-control-sm"
          placeholder="可选的描述"
          v-model.trim="info.description"
        />
      </td>
      <td>
        <button
          class="btn btn-sm btn-danger"
          @click.stop="removeAttachment(index)"
        >
          删除
        </button>
      </td>
    </tr>
    <tr>
      <input type="file" id="f" @change.stop="upload()" />
    </tr>
  </table>
</template>

<script>
import { uploadFile } from "@/api/upload.js";

export default {
  props: {
    attachments: {
      type: Array,
    },
    orderType: {
      type: Number,
    },
    orderId: {
      type: Number,
    },
  },
  data() {
    return {};
  },
  methods: {
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    showLoading: function (loadingText) {
      this.$store.commit("showLoading", {
        loading: true,
        loadingText: loadingText,
      });
    },
    hideLoading: function () {
      this.$store.commit("showLoading", { loading: false });
    },
    upload: function () {
      const objFile = document.getElementById("f");
      const files = objFile.files;
      if (files.length === 0) {
        this.showErrMsg("请选择文件");
        return;
      }

      const info = {
        fileName: "",
        description: "",
        blobId: 0,
      };

      info.fileName = files[0].name;

      const formData = new FormData();
      formData.append("upfile", files[0]);

      this.showLoading("上传中");

      uploadFile(
        formData,
        (v) => {
          if (v.status === "OK") {
            info.blobId = v.returnCode;
            this.attachments.push(info);
            objFile.value = "";
            this.showErrMsg("上传成功");
          } else {
            this.showErrMsg("上传失败：" + v.errmsg, "danger");
          }
        },
        (f) => {
          console.log(f);
          this.showErrMsg(
            "失败(" + f.status + ": " + f.statusText + ")",
            "danger"
          );
        },
        (v) => {
          this.hideLoading();
        }
      );
    },
    removeAttachment: function (idx) {
      this.$emit("remove", idx);
    },
  },
};
</script>